//
//  BBBViewController.m
//  iOSBase
//
//  Created by hc-apple on 2020/9/7.
//  Copyright © 2020 mac. All rights reserved.
//

#import "BBBViewController.h"
#import <PencilKit/PencilKit.h>
#import <WebKit/WebKit.h>

API_AVAILABLE(ios(13.0))
@interface BBBViewController ()<PKToolPickerObserver,PKCanvasViewDelegate>

@property(nonatomic,strong)PKToolPicker *toolPicker;
@property(nonatomic,strong)PKCanvasView *canvasView;

@property(nonatomic,strong)WKWebView *wkWebView;

@end

@implementation BBBViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor blackColor];
    
    self.canvasView = [[PKCanvasView alloc] initWithFrame:CGRectMake(10, 100, KScreenWidth-20, KScreenHeight-300)];
    self.canvasView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.1];
    self.canvasView.delegate = self;
    //self.canvasView.drawingGestureRecognizer =
    self.canvasView.alwaysBounceVertical = YES;
    [self.view addSubview:self.canvasView];
    
    self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(10, 100, KScreenWidth-20, KScreenHeight-300)];
    [self loadPDF:@"ttt.pdf" inWebView:self.wkWebView];
    [self.view addSubview:self.wkWebView];
    [self.view insertSubview:self.wkWebView belowSubview:self.canvasView];
    NSLog(@"子视图-%@",self.canvasView.subviews);
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.toolPicker = [PKToolPicker sharedToolPickerForWindow:[UIApplication sharedApplication].windows.firstObject];
        [self.toolPicker setVisible:YES forFirstResponder:self.canvasView];
        [self.toolPicker addObserver:self.canvasView];
        [self.toolPicker addObserver:self];
        [self.canvasView becomeFirstResponder];
    });
}

- (IBAction)toolsaction:(id)sender {
//    UIImage *img = [self screenShotView:self.canvasView];
//    UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);

}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}


//#pragma -mark -functions
//// 对指定视图进行截图
//- (UIImage *)screenShotView:(UIView *)view
//{
//    UIImage *imageRet = nil;
//
//    if (view)
//    {
//        if(&UIGraphicsBeginImageContextWithOptions)
//        {
//            UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
//        }
//        else
//        {
//            UIGraphicsBeginImageContext(view.frame.size);
//        }
//
//        //获取图像
//        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
//        imageRet = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//    }else{
//    }
//
//    return imageRet;
//}

-(void)loadPDF:(NSString*)fileName inWebView:(WKWebView*)webView{
    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    NSURL *url = [NSURL fileURLWithPath:path];
    [webView loadFileURL:url allowingReadAccessToURL:url];
}



-(NSMutableData*)createPDFfromUIScrollView:(UIScrollView*)scrollView {
    
    //存储ScrollView的初始位置及父视图
    CGRect origRect = scrollView.frame;
    UIView *origSuperView = scrollView.superview;
    
    //此处可以做一些子视图的处理，比如忽略ScrollView上一些图片的打印，需要将该图片视图进行适时的隐藏
    
    //创建一个新的用来显示的pdf的大小，这里为内容上下各预留了20的偏移
    CGRect rootRect = CGRectMake(0, 0, 595, scrollView.contentSize.height + 40);
    //重新计算scrollview的frame，新frame处于背景的中间，同时，为了能打印所有内容，将size设置为contentsize
    CGRect newScrollRect = CGRectMake((595 - scrollView.contentSize.width) / 2., 20, scrollView.contentSize.width, scrollView.contentSize.height);
    //重新为scrollview设置frame，并从原父视图移除
    [scrollView removeFromSuperview];
    scrollView.frame = newScrollRect;
    
    //设置背景图，这里的背景图宽度为A4的宽度595
    UIView *rootView = [[UIView alloc] initWithFrame:rootRect];
    rootView.backgroundColor = [UIColor whiteColor];
    //将需要打印的内容放置在新的背景图上
    [rootView addSubview:scrollView];
    
    //声明存储打印数据的数据结构
    NSMutableData *pdfData = [NSMutableData data];
    //设置要打印出来的文件的宽高
    UIGraphicsBeginPDFContextToData(pdfData, rootRect, nil);
    //开始打印
    UIGraphicsBeginPDFPage();
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();
    [rootView.layer renderInContext:pdfContext];
    //结束打印
    UIGraphicsEndPDFContext();
    
    //将scrollview的frame与父视图设置为初始状态
    scrollView.frame = origRect;
    [origSuperView addSubview:scrollView];
    
    //此处对可以进行对子视图的恢复，比如说图片视图的恢复显示
    
    //输出打印数据，根据需要进行数据的存储或传输
    return pdfData;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
